﻿using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;
using RotovapPlatform.UI.ViewModels.DeviceMaintenance.ManualOperation;
using System;
using Microsoft.Extensions.Logging;
using RotovapPlatform.Domain.Equipment.Interfaces.Services;

namespace RotovapPlatform.UI.Views.DeviceMaintenance.ManualOperation
{
	/// <summary>
	/// ManualIOView.xaml 的交互逻辑
	/// </summary>
	public partial class ManualIOView : UserControl
	{
		private ManualIOViewModel _viewModel;
		private ILogger<ManualIOView> _logger;
		private IDeviceStatusService _deviceStatusService;

		public ManualIOView()
		{
			InitializeComponent();

			// 直接从DI容器获取ViewModel和其他服务
			_viewModel = App.ServiceProvider.GetRequiredService<ManualIOViewModel>();
			_logger = App.ServiceProvider.GetRequiredService<ILogger<ManualIOView>>();
			_deviceStatusService = App.ServiceProvider.GetRequiredService<IDeviceStatusService>();

			DataContext = _viewModel;

			// 注册页面生命周期事件
			Loaded += ManualIOView_Loaded;
			Unloaded += ManualIOView_Unloaded;
		}

		private void ManualIOView_Loaded(object sender, System.Windows.RoutedEventArgs e)
		{
			try
			{
				_logger?.LogInformation("ManualIOView页面已加载");

				// 重新初始化ViewModel
				_viewModel.Reinitialize();

				// 在页面加载时刷新IO信号
				_viewModel.RefreshIOSignalsCommand.ExecuteAsync(null);
			}
			catch (Exception ex)
			{
				_logger?.LogError(ex, "ManualIOView加载异常");
			}
		}

		private void ManualIOView_Unloaded(object sender, System.Windows.RoutedEventArgs e)
		{
			try
			{
				_logger?.LogInformation("ManualIOView页面已卸载");

				// 在页面卸载时释放ViewModel资源
				if (_viewModel is IDisposable disposable)
				{
					disposable.Dispose();
					_logger?.LogInformation("ManualIOViewModel已释放");
				}
			}
			catch (Exception ex)
			{
				_logger?.LogError(ex, "ManualIOView卸载异常");
			}
		}
	}
}